#include<pthread.h>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>

void* pthread_fun(void *arg)
{
    #if 0
    //设置线程取消状态为不可取消
    pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,NULL);
    #endif
    //设置线程取消状态为不可取消
    pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,NULL);
    //设置线程取消类型为不立即取消
    pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED,NULL);
    int i = 0;
    while(1)
    {
        printf("子线程执行%ds\n",++i);
        sleep(1);
        //设置线程取消点
        pthread_testcancel();
        #if 0
        if(i == 10)
        {
            pthread_testcancel();
        }
        #endif
    }
}
int main()
{
    printf("进程执行中...\n");
    pthread_t id;
    if(pthread_create(&id,NULL,pthread_fun,NULL) == -1)
    {
        perror("fail to pthread");
        exit(-1);
    }
    //运行3s后取消线程，发送终止信号
    sleep(3);
    if(pthread_cancel(id) != 0)
    {   
        perror("fail to cancel");
        exit(-1);
    }
    pthread_join(id,NULL);
    printf("进程退出\n");
    return 0;
}